﻿using Microsoft.Win32;
using PieControls;
using sorTV.Controller;
using sorTV.Interface;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace sorTV
{
    /// <summary>
    /// Interaction logic for Main.xaml
    /// </summary>
    public partial class Main : Window
    {
        private bool _isHeightExpanded = false;
        private bool _isWidthExpanded = false;
        private const int NORMAL_WIDTH = 780;
        private const int NORMAL_HEIGHT = 300;
        private const int EXPANDED_WIDTH = 1200;
        private const int EXPANDED_HEIGHT = 800;
        private const int DEFAULT_MANUELKØ = 30000;
        private const int DEFAULT_LOGUPDATEINTERVAL = 5000;
        private SystemController _scCon;
        private Timer _manuelKøTimer;
        private Timer _logUpdateTimer;

        private ListCollectionView _logColl;

        public Main()
        {
            _scCon = new SystemController();
            InitializeComponent();
            Start();
        }

        #region Manuel Kø Metoder
        public void ManuelKø()
        {
            _manuelKøTimer = new Timer(DEFAULT_MANUELKØ);
            _manuelKøTimer.Elapsed += timerAntalFiler_Elapsed;
            _manuelKøTimer.AutoReset = true;
            _manuelKøTimer.Start();
        }
        public delegate void SetAntalFiler();
        void timerAntalFiler_Elapsed(object sender, ElapsedEventArgs e)
        {
            textBlockAntalIKø.Dispatcher.Invoke(DispatcherPriority.Normal, new SetAntalFiler(UpdateAntalFiler));
        }

        public void UpdateAntalFiler()
        {
            textBlockAntalIKø.Text = "(" + _scCon.AntalManuelleFiler + ") Filer i kø til manuel behandling";
        } 

        public void ManuelKøNytInterval(int interval)
        {
           _manuelKøTimer.Interval = interval;
        }
        public void ManuelKøDefault()
        {
            _manuelKøTimer.Interval = DEFAULT_MANUELKØ;
        }
        #endregion

        #region Log Update Metoder
        public void LogUpdater()
        {
            _logUpdateTimer = new Timer(DEFAULT_LOGUPDATEINTERVAL);
            _logUpdateTimer.Elapsed += _logUpdateTimer_Elapsed;
            _logUpdateTimer.AutoReset = true;
            _logUpdateTimer.Start();
        }
        public delegate void LogUpdate();
        void _logUpdateTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            dgvLog.Dispatcher.Invoke(DispatcherPriority.Normal, new LogUpdate(UpdateDataGridLog));
        }

        public void UpdateDataGridLog()
        {
            _logColl = new ListCollectionView(_scCon.LogValues);
            
           

            if (textboxSøg.Text != string.Empty)
            {
                if (rbFilnavn.IsChecked == true)
                {
                    _logColl.Filter = o => (o as ILog).Filnavn.Contains(textboxSøg.Text);
                    
                }
                if (rbHandling.IsChecked == true)
                {
                    _logColl.Filter = o => (o as ILog).Handling.Contains(textboxSøg.Text);
                }
            
                dgvLog.ItemsSource = _logColl;
                textBlockAntalPoster.Text = _logColl.Count + " Poster fundet";
            }
            else
            {
                dgvLog.ItemsSource = _logColl;
                textBlockAntalPoster.Text = _logColl.Count + " Poster fundet";
            }
        }


        public void LogUpdateNytInterval(int interval)
        {
            _logUpdateTimer.Interval = interval;
        }
        public void LogUpdateDefault()
        {
            _logUpdateTimer.Interval = DEFAULT_LOGUPDATEINTERVAL;
        } 
        #endregion

        public void Start()
        {
             Width = NORMAL_WIDTH;
            Height = NORMAL_HEIGHT;
            ManuelKø();
            LogUpdater();
        }

        public void LogExporter()
        {
            string sti = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            if (!Directory.Exists(sti + @"\Logs"))
            {
                Directory.CreateDirectory(sti + @"\Logs");
            }
            string date = DateTime.Now.ToShortDateString();
            string time = DateTime.Now.ToLongTimeString().Replace(":","");
            StreamWriter sw = new StreamWriter(sti + @"\Logs\" + date + " " + time + " " + Environment.UserDomainName + "_Log.txt");
            sw.WriteLine("Timestamp | Handling | Filnavn");
            foreach (var item in _scCon.LogValues)
            {
                sw.WriteLine(item.Timestamp + " " + item.Handling + " " + item.Filnavn);
            }
            sw.Close();
        }

        private void btnLuk_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Vil du gemme loggen for denne kørsel?", "Gem Log", MessageBoxButton.YesNo, MessageBoxImage.Question);
            switch (result)
            {
                case MessageBoxResult.No:
                    Close();
                    break;
                case MessageBoxResult.Yes:
                    LogExporter();
                    Close();
                    break;
                default:
                    break;
            }
        }

        private void btnMinimize_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        public void CenterScreen()
        {
            if (_isHeightExpanded)
            {
                Top = (System.Windows.SystemParameters.PrimaryScreenHeight - EXPANDED_HEIGHT) / 2;
            }
            else
            {
                Top = (System.Windows.SystemParameters.PrimaryScreenHeight - NORMAL_HEIGHT) / 2;
            }

            if (_isWidthExpanded)
            {
                Left = (System.Windows.SystemParameters.PrimaryScreenWidth - EXPANDED_WIDTH) / 2;
            }
            else
            {
                Left = (System.Windows.SystemParameters.PrimaryScreenWidth - NORMAL_WIDTH) / 2;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (_isWidthExpanded)
            {
                btnLog.Content = "Vis Log";
                _isWidthExpanded = false;
                Width = NORMAL_WIDTH;
                CenterScreen();
            }
            else
            {
                btnLog.Content = "Skjul Log";
                _isWidthExpanded = true;
                Width = EXPANDED_WIDTH;
                CenterScreen();
            }
            
        }

        private void btnAdministrator_MouseEnter(object sender, MouseEventArgs e)
        {
            StackPanelBorder.Visibility = Visibility.Visible;
        }

        private void StackPanelBorder_MouseEnter(object sender, MouseEventArgs e)
        {
            StackPanelBorder.Visibility = Visibility.Visible;
        }

        private void btnAdministrator_MouseLeave(object sender, MouseEventArgs e)
        {
            StackPanelBorder.Visibility = Visibility.Collapsed;
        }

        private void StackPanelBorder_MouseLeave(object sender, MouseEventArgs e)
        {
            StackPanelBorder.Visibility = Visibility.Collapsed;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            tabControl.SelectedIndex = 1;
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            tabControl.SelectedIndex = 2;
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            tabControl.SelectedIndex = 3;
        }

        private void tabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tabItemOversigt.IsSelected)
            {

                ObservableCollection<PieSegment> pieCollection = new ObservableCollection<PieSegment>();
                foreach (var item in _scCon.Resultat)
                {
                    pieCollection.Add(new PieSegment { Name = item.Key, Value = item.Value });
                }
                foreach (var item in pieCollection)
                {
                    switch (item.Name)
                    {
                        case "Venstre, Danmarks Liberale Parti":
                            item.Color = Colors.RoyalBlue;
                            break;
                        case "Socialdemokratiet":
                            item.Color = Colors.IndianRed;
                            break;
                        case "SF - Socialistisk Folkeparti":
                            item.Color = Colors.Green;
                            break;
                        case "Radikale Venstre":
                            item.Color = Colors.Magenta;
                            break;
                        case "Liberal Alliance":
                            item.Color = Colors.Orange;
                            break;
                        case "Kristendemokraterne":
                            item.Color = Colors.Black;
                            break;
                        case "Enhedslisten - De Rød-Grønne":
                            item.Color = Colors.Yellow;
                            break;
                        case "Det Konservative Folkeparti":
                            item.Color = Colors.LightSeaGreen;
                            break;
                        case "Dansk Folkeparti":
                            item.Color = Colors.Wheat;
                            break;
                    }
                }
                pControl.Data = pieCollection;

               foreach (var item in pControl.Data)
                {
                    StackPanel legendHolder = new StackPanel();
                    legendHolder.Orientation = Orientation.Horizontal;
                    TextBlock color = new TextBlock();
                    color.Width = 15;
                    color.Height = 15;
                    SolidColorBrush brush = new SolidColorBrush(item.Color);
                    color.Background = brush;
                    TextBlock name = new TextBlock();
                    name.Text = item.Name;
                    name.Height = 15;
                  
                    legendHolder.Children.Add(color);
                    legendHolder.Children.Add(name);
                    legendHolder.Margin = new Thickness(2, 2, 2, 2);
                    wrapLegend.Children.Add(legendHolder);
                }
            }
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            if (_isHeightExpanded)
            {
                btnOpenManuel.Content = @"\/ ÅBEN \/";
                Height = NORMAL_HEIGHT;
                _isHeightExpanded = false;
                CenterScreen();
                stackPanelFilter.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                wrapPanelSøg.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                dgvLog.Height = 117;

                
            }
            else
            {
                btnOpenManuel.Content = "^ LUK ^";
                Height = EXPANDED_HEIGHT;
                _isHeightExpanded = true;
                CenterScreen();
                stackPanelFilter.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                wrapPanelSøg.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                dgvLog.Height = 600;
            }
        }

        private void btn0Kørsel_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Er Scriptet 'Drop and Create' kørt på databasen?", "Script afvikling", MessageBoxButton.YesNo);
            switch (result)
            {
                case MessageBoxResult.No:
                    MessageBox.Show("Kør scriptet hvis en 0-Kørsel er nødvendig", "Afbrudt", MessageBoxButton.OK, MessageBoxImage.Information);
                    break;
                case MessageBoxResult.Yes:
                    OpenFileDialog ofd = new OpenFileDialog();
                    ofd.Filter = ".xml |*xml";
                    ofd.ShowDialog();
                    if (ofd.FileName != "")
                    {
                        _scCon.NulKørsel(ofd.FileName);
                        MessageBox.Show("Kører 0-Kørsel", "0-Kørsel Startet", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                    }
                    else
                    {
                        MessageBox.Show("Fil ikke valgt", "0-Kørsel fejlet", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    break;
            }

            MessageBox.Show("Database 0-Kørt", "0-Kørsel", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            _scCon.NulstilXMLFeeds();
            MessageBox.Show("Alle filer nulstilet!", "XML Nulstilling", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            _scCon.Start();
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            _scCon.Stop();
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
                _scCon.Automatisk = true; 
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            _scCon.Automatisk = false;
        }

        private void chkManuelKø_Checked(object sender, RoutedEventArgs e)
        {
            if (_manuelKøTimer != null)
            {
                ManuelKøDefault();
            }
            cboManuelKø.IsEnabled = false;

        }

        private void chkLog_Checked(object sender, RoutedEventArgs e)
        {
            if (_logUpdateTimer != null)
            {
                LogUpdateDefault();                
            }
            cboLog.IsEnabled = false;
        }

        private void chkLog_Unchecked(object sender, RoutedEventArgs e)
        {
            cboLog.IsEnabled = true;
        }

        private void chkManuelKø_Unchecked(object sender, RoutedEventArgs e)
        {
            cboManuelKø.IsEnabled = true;
        }

        private void cboLog_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string value = cboLog.SelectedValue.ToString();
            MessageBox.Show(value);
            LogUpdateNytInterval(int.Parse(value));
        }

        private void cboManuelKø_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string value = cboManuelKø.SelectedValue.ToString();
            MessageBox.Show(value);
            ManuelKøNytInterval(int.Parse(value));
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (textboxSøg.Text != string.Empty)
            {
                if (rbFilnavn.IsChecked == true)
                {
                    _logColl.Filter = o => (o as ILog).Filnavn.Contains(textboxSøg.Text);

                }
                if (rbHandling.IsChecked == true)
                {
                    _logColl.Filter = o => (o as ILog).Handling.Contains(textboxSøg.Text.ToLower());
                }
                textBlockAntalPoster.Text = _logColl.Count + " Poster fundet";
                dgvLog.ItemsSource = _logColl;
            }

        }

        private void chkR1_Checked(object sender, RoutedEventArgs e)
        {
            _scCon.Regler[0] = true;
        }

        private void chkR1_Unchecked(object sender, RoutedEventArgs e)
        {
            _scCon.Regler[0] = false;
        }

        private void chkR2_Checked(object sender, RoutedEventArgs e)
        {
            _scCon.Regler[1] = true;
        }

        private void chkR2_Unchecked(object sender, RoutedEventArgs e)
        {
            _scCon.Regler[1] = false;
        }

        private void chkR3_Checked(object sender, RoutedEventArgs e)
        {
            _scCon.Regler[2] = true;
        }

        private void chkR3_Unchecked(object sender, RoutedEventArgs e)
        {
            _scCon.Regler[2] = false;
        }

        private void chkR4_Checked(object sender, RoutedEventArgs e)
        {
            _scCon.Regler[3] = true;
        }

        private void chkR4_Unchecked(object sender, RoutedEventArgs e)
        {
            _scCon.Regler[3] = false;
        }

    }
}
